import { useRequest } from 'ahooks'

import { useControllerRef } from '@/hooks/useAbortController'
import { useRequestSyncStorePlugin } from '@/hooks/useRequestSyncStorePlugin'
import { apiGetEventTemplateList } from './apis'
import { IEventTemplateReq, IEventTemplateRes } from './interface'
import { useBoundStore } from './store'

export const useEventTemplateList = () => {
  const controllerRef = useControllerRef()
  const getTabCount = useBoundStore(state => state.getTabCount)

  const requestSyncStorePlugin = useRequestSyncStorePlugin({
    onMaybeChange: request => useBoundStore.setState({ request }),
  })

  useRequest<IEventTemplateRes, [IEventTemplateReq]>(
    req => {
      controllerRef.current.abort()
      controllerRef.current = new AbortController()
      getTabCount(req)
      return apiGetEventTemplateList(req, controllerRef.current.signal)
    },
    {
      defaultParams: [useBoundStore.getState().reqData],
    },
    [requestSyncStorePlugin],
  )
}
